package com.xbai.oauth.controller;

import com.xbai.entity.Result;
import com.xbai.entity.StatusCode;
import com.xbai.oauth.service.AuthService;
import com.xbai.oauth.util.AuthToken;
import com.xbai.oauth.util.CookieUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * @author jxbai
 * @desc
 * @date 2021/2/5 0005
 */
@RestController
@RequestMapping(value = "/user")
@RequiredArgsConstructor
public class AuthController {

    /**
     * 客户端ID
     */
    @Value("${auth.clientId}")
    private String clientId;

    /**
     * 秘钥
     */
    @Value("${auth.clientSecret}")
    private String clientSecret;

    /**
     * Cookie存储的域名
     */
    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    /**
     * Cookie生命周期
     */
    @Value("${auth.cookieMaxAge}")
    private Integer cookieMaxAge;

    private final AuthService authService;

    @PostMapping("/login")
    public Result login(String username, String password) {
        if (StringUtils.isEmpty(username)) {
            throw new RuntimeException("用户名不允许为空");
        }
        if (StringUtils.isEmpty(password)) {
            throw new RuntimeException("密码不允许为空");
        }
        //申请令牌
        AuthToken authToken = authService.login(username, password, clientId, clientSecret);

        //用户身份令牌
        String accessToken = authToken.getAccessToken();

        //将令牌存储到cookie
        saveCookie(accessToken);
        return new Result(true, StatusCode.OK,"登录成功！");
    }

    /**
     * 将令牌存储到cookie
     * @param token 令牌
     */
    private void saveCookie(String token) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        CookieUtil.addCookie(response, cookieDomain, "/", "Authorization", token, cookieMaxAge, false);
    }
}
